package com.example.chatchatbackend.handler;

import com.example.chatchatbackend.entity.vo.response.MessageVO;
import com.example.chatchatbackend.entity.vo.response.SendMessageVO;
import com.example.chatchatbackend.service.MessageService;
import com.example.chatchatbackend.service.sendJob.SendMessageService;
import com.example.chatchatbackend.utils.TimeUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class MessageHandler {

    @Resource
    private MessageService messageService; // 假设有一个服务类用于处理数据库操作

    @Resource
    private SendMessageService sendMessageService;

    private static final LocalDateTime currentTime = TimeUtil.Time_Now.getCurrentTime();

    @XxlJob("messageTaskHandler")
    public void execute() {

        XxlJobHelper.log("Xxl-Job:Insert");

        // 查询发送时间小于当前时间且未发送的任务
        List<SendMessageVO> tasksToSend = sendMessageService.findTasksToSend(this.currentTime);
        if(tasksToSend.isEmpty()){
            XxlJobHelper.log("无需更新，所有记录已发送");
            return;
        }

        SendMessageVO sendMessageVO = tasksToSend.get(0);

        MessageVO messageVO = new MessageVO();
        BeanUtils.copyProperties(sendMessageVO, messageVO);
        messageVO.setIsRespond(1);
        messageVO.setIsRobot(1);
        messageService.insertMessage(messageVO);

        sendMessageService.updateIsSend(sendMessageVO);
        XxlJobHelper.log("成功插入Message：{}",messageVO);

    }

}
